package com.xianlai.ad.top_on_ad_plugin.splash

import android.app.Activity
import android.content.Context
import android.view.ViewGroup
import com.anythink.core.api.ATAdInfo
import com.anythink.core.api.ATSDK
import com.anythink.core.api.AdError
import com.anythink.splashad.api.*
import com.xianlai.ad.ad_common.splash.ISplashSkipView
import com.xianlai.ad.ad_common.splash.ThirdSplashAd
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

class ToponSplashAd(context: Context, appId: String, appKey: String, placementId: String)
    : ThirdSplashAd(context, appId, appKey, placementId) {

    private var atSplashAd: ATSplashAd? = null
    private var showingAd: ATAdInfo? = null

    private val adLoadStatusListeners: MutableList<ThirdSplashAdStatusListener> = mutableListOf()

    override fun init() {

        ATSDK.init(context, appId, appKey)

        atSplashAd = ATSplashAd(context, placementId, object : ATSplashAdListener {
            override fun onAdLoaded(isTimeout: Boolean) {
                val detailMap = createAdDetailMap(atSplashAd?.checkAdStatus()?.atTopAdInfo)
                adLoadStatusListeners.toTypedArray().forEach {
                    it.onAdLoaded(isTimeout, detailMap)
                }
            }

            override fun onAdLoadTimeout() {
                adLoadStatusListeners.toTypedArray().forEach {
                    it.onAdLoadTimeout()
                }
            }

            override fun onNoAdError(p0: AdError?) {
                adLoadStatusListeners.toTypedArray().forEach {
                    it.onNoAdError(p0?.code ?: "", (p0?.desc
                            ?: "") + "    platformMSG:" + (p0?.platformMSG ?: ""))
                }
            }

            override fun onAdShow(p0: ATAdInfo?) {
                showingAd = p0
                val detailMap = createAdDetailMap(p0)
                adLoadStatusListeners.toTypedArray().forEach {
                    it.onAdShow(detailMap)
                }
            }

            override fun onAdClick(p0: ATAdInfo?) {
                adLoadStatusListeners.toTypedArray().forEach {
                    it.onAdClick()
                }
            }

            override fun onAdDismiss(p0: ATAdInfo?, p1: ATSplashAdExtraInfo?) {
                showingAd = null
                adLoadStatusListeners.toTypedArray().forEach {
                    it.onAdDismiss()
                }
            }
        })
    }

    override suspend fun load(): Boolean = suspendCancellableCoroutine { continuation ->
        if (atSplashAd == null) {
            continuation.resume(false)
            return@suspendCancellableCoroutine
        }
        if (atSplashAd!!.isAdReady) {
            continuation.resume(true)
            return@suspendCancellableCoroutine
        }
        val listener = object : ThirdSplashAdStatusListener {

            override fun onAdLoaded(isTimeout: Boolean, detailMap: Map<String, Any>) {
                adLoadStatusListeners.remove(this)
                continuation.resume(!isTimeout)
            }

            override fun onAdLoadTimeout() {
                adLoadStatusListeners.remove(this)
                continuation.resume(false)
            }

            override fun onNoAdError(code: String, desc: String) {
                adLoadStatusListeners.remove(this)
                continuation.resume(false)
            }

            override fun onAdShow(detailMap: Map<String, Any>) {}

            override fun onAdClick() {}

            override fun onAdDismiss() {}
        }
        adLoadStatusListeners.add(listener)
        atSplashAd!!.loadAd()
    }

    override fun isReady(): Boolean {
        return atSplashAd?.isAdReady == true
    }

    override fun isShowing(): Boolean {
        return showingAd != null
    }

    override fun setThirdSplashAdStatusListener(listener: ThirdSplashAdStatusListener) {
        adLoadStatusListeners.add(listener)
    }

    override suspend fun show(activity: Activity,
                              viewGroup: ViewGroup,
                              skipView: ISplashSkipView?)
            : Boolean = suspendCancellableCoroutine { continuation ->
        if (atSplashAd?.isAdReady != true) {
            continuation.resume(false)
            return@suspendCancellableCoroutine
        }
        var atSplashSkipInfo: ATSplashSkipInfo? = null
        if (skipView != null) {
            atSplashSkipInfo = ATSplashSkipInfo(skipView.getSkipView(),
                    skipView.countDownDuration,
                    skipView.callbackInterval,
                    object : ATSplashSkipAdListener {
                        override fun onAdTick(p0: Long, p1: Long) {
                            skipView.onAdTick(p0, p1)
                        }

                        override fun isSupportCustomSkipView(p0: Boolean) {
                            skipView.isSupportCustomSkipView(p0)
                        }
                    })
        }
        val listener = object : ThirdSplashAdStatusListener {

            override fun onAdLoaded(isTimeout: Boolean, detailMap: Map<String, Any>) {}

            override fun onAdLoadTimeout() {}

            override fun onNoAdError(code: String, desc: String) {}

            override fun onAdShow(detailMap: Map<String, Any>) {}

            override fun onAdClick() {}

            override fun onAdDismiss() {
                adLoadStatusListeners.remove(this)
                continuation.resume(true)
            }
        }
        adLoadStatusListeners.add(listener)
        atSplashAd!!.show(activity, viewGroup, atSplashSkipInfo)
    }


    /**
     * "id"：对应getShowId()
    "publisher_revenue"：对应getPublisherRevenue()
    "currency"：对应 getCurrency()
    "country"：对应 getCountry()
    "adunit_id"：对应 getTopOnPlacementId()
    "adunit_format"：对应 getTopOnAdFormat()
    "precision"：对应 getEcpmPrecision()
    "network_type"：对应 getAdNetworkType()
    "network_placement_id"：对应 getNetworkPlacementId()
    "ecpm_level"：对应 getEcpmLevel()
    "segment_id"：对应 getSegmentId()
    "scenario_id"：对应 getScenarioId()
    "scenario_reward_name"：对应 getScenarioRewardName()
    "scenario_reward_number"：对应 getScenarioRewardNumber()
    "channel"：对应 getChannel()
    "sub_channel"：对应 getSubChannel()
    "custom_rule"：对应 getCustomRule()
    "network_firm_id"：对应 getNetworkFirmId()
    "adsource_id"：对应 getAdsourceId()
    "adsource_index"：对应 getAdsourceIndex()
    "adsource_price"：对应 getEcpm()
    "adsource_isheaderbidding"：对应 isHeaderBiddingAdsource()
     */
    private fun createAdDetailMap(atAdInfo: ATAdInfo?): Map<String, Any> {
        val map: MutableMap<String, Any> = mutableMapOf()
        if (atAdInfo == null) {
            return map;
        }
        map["adsource_id"] = atAdInfo.adsourceId ?: ""
        map["segment_id"] = atAdInfo.segmentId
        map["adsource_price"] = atAdInfo.ecpm
        map["adsource_index"] = atAdInfo.adsourceIndex
        map["adsource_isheaderbidding"] = atAdInfo.isHeaderBiddingAdsource
        map["adunit_format"] = atAdInfo.topOnAdFormat ?: ""
        map["currency"] = atAdInfo.currency ?: ""
        map["ecpm_level"] = atAdInfo.ecpmLevel
        map["network_firm_id"] = atAdInfo.networkFirmId
        map["precision"] = atAdInfo.ecpmPrecision ?: ""
        map["publisher_revenue"] = atAdInfo.publisherRevenue
        map["scenario_id"] = atAdInfo.scenarioId ?: ""
        map["scenario_reward_name"] = atAdInfo.scenarioRewardName ?: ""
        map["scenario_reward_number"] = atAdInfo.scenarioRewardNumber
        map["id"] = atAdInfo.showId ?: ""
        map["network_placement_id"] = atAdInfo.networkPlacementId ?: ""
        return map;
    }
}